//package com.advert.boot.system.controller;
//
//import cn.hutool.core.date.DateUtil;
//import com.advert.boot.common.result.Result;
//import com.advert.boot.config.WechatPayConfig;
//import com.advert.boot.config.property.WxPayProperties;
//import com.wechat.pay.java.core.exception.ValidationException;
//import com.wechat.pay.java.core.notification.NotificationConfig;
//import com.wechat.pay.java.core.notification.NotificationParser;
//import com.wechat.pay.java.core.notification.RequestParam;
//import com.wechat.pay.java.service.partnerpayments.nativepay.NativePayService;
//import com.wechat.pay.java.service.payments.app.model.PrepayRequest;
//import com.wechat.pay.java.service.refund.RefundService;
//import com.wechat.pay.java.service.refund.model.*;
//import io.swagger.v3.oas.annotations.Operation;
//import io.swagger.v3.oas.annotations.tags.Tag;
//import jakarta.servlet.http.HttpServletRequest;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.time.DateUtils;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//
//import java.math.BigDecimal;
//import java.util.Calendar;
//import java.util.Date;
//
//
//@RestController
////@RequiredArgsConstructor
//@Tag(name = "16.wxPay")
//@RequestMapping("/wxPay")
//@Slf4j
//public class WxPayController {
////    private final WxPayService wxPayService;
////    private final WxPayProperties wxPayConfig;
////    private final WebMvcConfigurer webMvcConfigurer;
//
//
//
//
//
//
//    /**
//     * 微信 Native 支付下单
//     *
//     * @param amt         金额
//     * @param orderNumber 订单号
//     * @param description 描述
//     * @return 二维码链接
//     */
//    @Operation(summary = "微信 Native 支付下单")
//    @GetMapping("/pay1")
//    public static Result<?> nativePay(BigDecimal amt, String orderNumber, String description) {
//        // 当前时间
//        Date currentDate = new Date();
//        // 将金额转换为分
//        int total = amt.multiply(new BigDecimal("100")).intValue();
//        try {
//            // 构建service
//            NativePayService service = new NativePayService.Builder().config(WechatPayConfig.config).build();
//            // 构建请求对象
//            com.wechat.pay.java.service.partnerpayments.nativepay.model.PrepayRequest request = new com.wechat.pay.java.service.partnerpayments.nativepay.model.PrepayRequest();
//            request.setSpAppid(WechatPayConfig.appid);
//            request.setSpMchid(WechatPayConfig.merchantId);
//            request.setNotifyUrl(WechatPayConfig.notifyUrl);
//            // 设置金额
//            com.wechat.pay.java.service.partnerpayments.nativepay.model.Amount amount = new com.wechat.pay.java.service.partnerpayments.nativepay.model.Amount();
//            amount.setTotal(total);
//            request.setAmount(amount);
//            request.setDescription(description);
//            request.setOutTradeNo(orderNumber);
//            request.setSubMchid("8");
//            // 计算订单失效时间
//            Calendar calendar = DateUtils.toCalendar(currentDate);
//            calendar.add(Calendar.MINUTE, WechatPayConfig.ORDER_PAY_TIME_OUT);//2023-04-01T13:00:00Z
//            request.setTimeExpire(/*DateUtil.now()*/"2025-06-27T23:26:00Z"/*DateUtils.parseDateToStr("yyyy-MM-dd'T'HH:mm:ss+08:00", calendar.getTime())*/);
//            return Result.success(service.prepay(request).getCodeUrl());
//        } catch (Exception e){
//            log.error(e.getMessage(),e);
//            return Result.failed("支付订单创建失败");
//        }
//    }
//
////
////    /**
////     * 微信支付回调
////     *
////     * @return 回调结果
////     */
////    @PostMapping("/wechat")
////    public ResponseEntity.BodyBuilder wechat(@RequestBody String body, HttpServletRequest request) {
////        try {
////            // 构造 RequestParam
////            RequestParam requestParam = new RequestParam.Builder()
////                    // 序列号
////                    .serialNumber(request.getHeader("Wechatpay-Serial"))
////                    // 随机数
////                    .nonce(request.getHeader("Wechatpay-Nonce"))
////                    // 签名
////                    .signature(request.getHeader("Wechatpay-Signature"))
////                    // 时间戳
////                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
////                    .body(body)
////                    .build();
////            // 初始化解析器
////            NotificationParser parser = new NotificationParser((NotificationConfig) WechatPayConfig.config);
////            // 验签、解密并转换成 Transaction
////            Transaction transaction = parser.parse(requestParam, Transaction.class);
////            // 校验交易状态
////            if (Transaction.TradeStateEnum.SUCCESS.equals(transaction.getTradeState())) {
////                // 支付成功，根据订单编号查询订单信息
////                // 1.查询订单信息
////                Order orderOld = orderService.selectForUpdateByOrderNumber(transaction.getOutTradeNo());
////                // 校验金额
////                if (orderOld != null && orderOld.getPayAmount().equals(transaction.getAmount().getTotal())) {
////                    // 金额相等 完成支付 更新订单状态
////                    WechatPayUtil.success(orderOld,transaction);
////                } else {
////                    // 金额异常 执行退款
////                    WechatPayUtil.refunded(new WechatPayRedis(transaction.getOutTradeNo(), transaction.getAmount().getTotal(), null));
////                }
////            }
////        } catch (ValidationException e) {
////            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
////            return ResponseEntity.status(HttpStatus.UNAUTHORIZED);
////        }
////
////        // 处理成功，返回 200 OK 状态码
////        return ResponseEntity.status(HttpStatus.OK);
////    }
////
////    /**
////     * 支付成功
////     */
////    public static void success( Order orderOld,Transaction transaction) {
////        try {
////            // 支付完成时间
////            Date payTime = DateUtils.parseDate(transaction.getSuccessTime(), "yyyy-MM-dd'T'HH:mm:ss+08:00");
////            // 校验订单信息 & 支付结果 & 订单有效期止日期
////            if (orderOld != null && orderOld.getPayResult() == 0 && payTime.compareTo(orderOld.getExpirationDate()) < 1) {
////                // 构建修改对象
////                Order updateOrder = new Order();
////                updateOrder.setId(orderOld.getId());
////                updateOrder.setPayMethod(PayMethodEnum.W.name());
////                updateOrder.setPayChannel(PayChannelEnum.P.name());
////                updateOrder.setPayDate(payTime);
////                updateOrder.setPayResult(PayResultEnum.PAID.getCode());
////                updateOrder.setPayType(PayTypeEnum.U.name());
////                updateOrder.setSerialNumber(transaction.getTransactionId());
////                if (orderService.editPayResult(updateOrder,orderOld) == 1) {
////                    // 删除Redis订单支付信息
////                    SpringUtils.getBean(RedisCache.class).deleteObject(WechatPayConfig.ORDER_PAY_REDIS_PREFIX + transaction.getOutTradeNo());
////                }
////            } else {
////                // 订单信息不存在 执行退款
////                WechatPayUtil.refunded(new WechatPayRedis(transaction.getOutTradeNo(), transaction.getAmount().getTotal(), null));
////            }
////        } catch (Exception e) {
////            log.error(e.getMessage(), e);
////        }
////    }
////
////    /**
////     * 执行退款
////     */
////    public static void refunded(WechatPayRedis wechatPay) {
////        try {
////            // 构建退款Service
////            RefundService service = new RefundService.Builder().config(WechatPayConfig.config).build();
////            // 构建请求对象
////            CreateRequest request = new CreateRequest();
////            request.setOutTradeNo(wechatPay.getOrderNumber());
////            request.setOutRefundNo(wechatPay.getOrderNumber());
////            // 支付总金额（分）
////            long total = wechatPay.getTotal();
////            // 设置退款金额
////            AmountReq amount = new AmountReq();
////            amount.setRefund(total);
////            amount.setTotal(total);
////            amount.setCurrency("CNY");
////            request.setAmount(amount);
////            // 请求API申请退款
////            Refund refund = service.create(request);
////            // 校验退款结果
////            if (refund != null && Status.SUCCESS.equals(refund.getStatus())) {
////                // 退款成功
////                log.info("微信退款成功：{}", wechatPay);
////            }
////        } catch (Exception e) {
////            log.error(e.getMessage(), e);
////        }
////    }
//
//
//
//
//
//
//
//
//
//
//  /*  *//**
//     * 微信支付 生成二维码
//     *
//     * @param money money
//     *//*
//    @GetMapping("/pay")
//    public void wxPay(Double money, String body, Integer uid, HttpServletResponse response) {
//        Double amount = 10d;//money;//金额
//        SimpleDateFormat date = new SimpleDateFormat("yyyyMMddHHmmss");
//        String orderNo = date.format(new Date()) + WxChatPayUtils.getCurrentTimestampMs();
//        String url_code = wxPayService.save(orderNo, amount, body, uid);
//        System.out.println("url_code:----------" + url_code);
//        if (url_code == null) {
//            throw new NullPointerException();
//        }
//
//        try {
//          *//*  // 生成二维码配置
//            Map<EncodeHintType, Object> hints = new HashMap<>();
//            // 设置纠错等级
//            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
//            // 编码类型
//            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//
//            BitMatrix bitMatrix = new MultiFormatWriter().encode(url_code, BarcodeFormat.QR_CODE, 400, 400, hints);
//            OutputStream outputStream = response.getOutputStream();
//
//            MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);*//*
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }*/
//
//  /*  *//**
//     * 微信支付回调接口
//     *//*
//    @RequestMapping("/callback")
//    public void OrderCallBack(HttpServletRequest request, HttpServletResponse response) {
//        InputStream inputStream;
//        try {
//            inputStream = request.getInputStream();
//            // BufferedReader是包装设计模式，性能更高
//            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
//            StringBuilder stringBuffer = new StringBuilder();
//            String line;
//            while ((line = bufferedReader.readLine()) != null) {
//                stringBuffer.append(line);
//            }
//            bufferedReader.close();
//            inputStream.close();
//            Map<String, String> callBackMap = WxChatPayUtils.xmlToMap(stringBuffer.toString());
//            System.out.println(callBackMap);
//
//            SortedMap<String, String> sortedMap = WxChatPayUtils.getSortedMap(callBackMap);
//            // 校验签名是否正确
//            if (WxChatPayUtils.isCorrectSign(sortedMap, wxPayConfig.getKey())) {
//                System.out.println("签名校验成功！");
//                // 更新订单状态
//                if (!"SUCCESS".equals(sortedMap.get("result_code"))) {
//                    // 未成功，就都处理为失败订单
//                    response.setContentType("text/html");
//                    response.getWriter().println("fail");
//                }
//
//                String outTradeNo = sortedMap.get("out_trade_no"); // 流水号
//                String totalFee = sortedMap.get("total_fee"); // 交易金额
//                if (wxPayService.callBackPayUpdate(outTradeNo, totalFee)) {  // 通知微信订单处理成功
//                    response.setContentType("text/xml");
////                    response.setContentType("content-type");
//                    response.getWriter().println("<xml> <return_code><![CDATA[SUCCESS]]></return_code> <return_msg><![CDATA[OK]]></return_msg> </xml>");
//                    //这里说明告诉微信你已经成功啦，别给老子重复回调我的方法啦，这里有一个坑，
//                    response.setContentType("text/xml");
//                    response.getWriter().println("SUCCESS");
//                    //本身我就只有这两句话，然后就导致微信一直回调我的方法，废了半天的劲才搞好啦，
//                    //原因就是格式不对，给他返回的值他不认识，这里可以看一下微信的支付开发文档，虽然文档写的很垃圾
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    *//**
//     * 下单 生成二维码
//     *//*
//    @GetMapping("/createNative/{orderId}")
//    public Result<?> createNative1(@PathVariable("orderId") Long orderId) {
////        Map map = this.createNative(orderId);
//
//        // TODO Auto-generated method stub
//        String nonce_str = "PayCommonUtil.getNonce_str()";
//        long time_stamp = System.currentTimeMillis() / 1000;
//        String product_id = "hd_goodsssss_10";
//        String key = "PayConfigUtil.API_KEY"; // key
//
//        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
//        packageParams.put("appid", PayConfigUtil.APP_ID);
//        packageParams.put("mch_id", PayConfigUtil.MCH_ID);
//        packageParams.put("time_stamp", String.valueOf(time_stamp));
//        packageParams.put("nonce_str", nonce_str);
//        packageParams.put("product_id", product_id);
//        String sign = PayCommonUtil.createSign("UTF-8", packageParams,key);//MD5哈希
//        packageParams.put("sign", sign);
//
//        //生成参数
//        String str = ToUrlParams(packageParams);
//        String payurl = "weixin://wxpay/bizpayurl?" + str;
//        System.out.println("payurl:"+payurl);
//
//
//        //生成二维码
//        Map<EncodeHintType, Object>  hints=new HashMap<EncodeHintType, Object>();
//        // 指定纠错等级
//        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
//        // 指定编码格式
//        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//        hints.put(EncodeHintType.MARGIN, 1);
//        try {
//            BitMatrix bitMatrix = new MultiFormatWriter().encode(payurl,BarcodeFormat.QR_CODE, defaultWidthAndHeight, defaultWidthAndHeight, hints);
//            OutputStream out = response.getOutputStream();
//            MatrixToImageWriter.writeToStream(bitMatrix, "png", out);//输出二维码
//            out.flush();
//            out.close();
//
//        } catch (WriterException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//
//        return Result.success();
//    }
//
//
//
//    //生成支付的二维码
//    public Map createNative(Long orderId) {
//        //支付记录表添加数据
//        //根据单号查询订单相关信息
//        OrderInfo orderInfo = orderInfoService.getById(orderId);
//        if (orderInfo == null) {
//            throw new BusinessException(ResultCode.USER_RESOURCE_EXCEPTION, "订单不存在");
//        }
//        //添加订单状态
//        paymentInfoService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
//        //调用微信接口返回二维码
//        try {
//            //2 调用微信接口，得到二维码地址等信息
//            //封装传递微信地址参数
//            Map paramMap = new HashMap();
//            paramMap.put("appid", wxPayConfig.getAppID()); //公众号id
//            paramMap.put("mch_id", wxPayConfig.getMchID()); //商户号
//            paramMap.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符串，调用工具类
//
////            Date reserveDate = orderInfo.getReserveDate();
//            String reserveDateString = DateUtil.today(); //new DateTime(reserveDate).toString("yyyy/MM/dd");
//            String body = reserveDateString + "就诊" *//*+ orderInfo.getDepname()*//*;
//            paramMap.put("body", body);//扫码后手机显示内容
//
//            paramMap.put("out_trade_no", orderInfo.getOutTradeNo()); //订单流水号
//            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
//            paramMap.put("total_fee", "1");//TODO 为了测试  支付金额
//            paramMap.put("spbill_create_ip", "127.0.0.1");  //终端ip
//            paramMap.put("notify_url", "http://xxxxxxxxx");//回调地址
//            paramMap.put("trade_type", "NATIVE"); //二维码类型
//            //请求微信生成二维码接口
//            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
//            //设置post请求相关参数
//            //微信支付要求传递参数xml格式
//            //把封装map集合变成xml，加密处理，传输
//            String xml = WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY);
//            client.setXmlParam(xml);
//            //支持https协议
//            client.setHttps(true);
//            //发送
//            client.post();
//
//            //调用微信接口，返回数据,xml格式的数据
//            String resultXml = client.getContent();
//            System.out.println("微信二维码：" + resultXml);
//            //把xml格式数据转换map
//            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
//
//            Map map = new HashMap<>();
//            map.put("orderId", orderId);
//            map.put("totalFee", orderInfo.getAmount());
//            map.put("resultCode", resultMap.get("result_code"));
//            map.put("codeUrl", resultMap.get("code_url"));  //微信二维码地址
//
//            return map;
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new BusinessException(ResultCode.USER_REQUEST_SERVICE_EXCEPTION, "生成二维码失败");
//        }
//    }*/
//}